
export function formatDate (date, fmt) {
  const o = {
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'h+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds(),
    'q+': Math.floor((date.getMonth() + 3) / 3),
    S: date.getMilliseconds()
  }
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  }
  for (var k in o) {
    if (new RegExp('(' + k + ')').test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
    }
  }
  return fmt
}

export function getTime (val) {
  if (typeOf(val) === 'number') return val
  return dateReplace(val).getTime()
}

function dateReplace (val) {
  let date = ''
  if (val && typeof val === 'string') {
    if (val.includes('-')) date = val.replace(/-/g, '/')
    else date = val
  }
  return new Date(date)
}

export function isNumber (num) {
  return typeOf(num) === 'number'
}

export function isString (str) {
  return typeOf(str) === 'string'
}

export function isArray (arr) {
  return typeOf(arr) === 'array'
}

export function isEmpty (str) {
  if (isArray(str)) return Boolean(!str.length)
  else {
    // eslint-disable-next-line
    if (typeof str === 'undefined' || str === null || !(str === str) || str.toString().includes('NaN')) str = ''
    const reg = new RegExp(/^[\s]*$/)
    str = trim(str)
    return reg.test(str)
  }
}

export function isDev () {
  return process.env.NODE_ENV === 'development'
}

export function trim (str) {
  if (String.prototype.trim) {
    return str === null ? '' : String.prototype.trim.call(str)
  } else {
    return str.replace(/(^\s*)|(\s*$)/g, '')
  }
}

export function typeOf(obj) {
  const toString = Object.prototype.toString;
  const map = {
      '[object Boolean]'  : 'boolean',
      '[object Number]'   : 'number',
      '[object String]'   : 'string',
      '[object Function]' : 'function',
      '[object Array]'    : 'array',
      '[object Date]'     : 'date',
      '[object RegExp]'   : 'regExp',
      '[object Undefined]': 'undefined',
      '[object Null]'     : 'null',
      '[object Object]'   : 'object'
  };
  return map[toString.call(obj)];
}

export function deepCopy (data) {
  const t = typeOf(data)
  let o

  if (t === 'array') {
    o = []
  } else if (t === 'object') {
    o = {}
  } else {
    return data
  }

  if (t === 'array') {
    for (let i = 0; i < data.length; i++) {
      o.push(deepCopy(data[i]))
    }
  } else if (t === 'object') {
    for (let i in data) {
      o[i] = deepCopy(data[i])
    }
  }
  return o
}

/**
 * 枚举转换表格数据
 * @param {*} arr  枚举列表
 * @param {*} fmtLabel
 * @param {*} fmtValue
 * @returns
 */
 export function dataProvider (arr, fmtLabel = 'label', fmtValue = 'value') {
  let obj = {}
  if (typeOf(arr) !== 'array') {
    console.log('dataProvider must input array')
    return
  }
  arr.forEach(r => {
    obj[r[fmtValue]] = r[fmtLabel]
  })
  return obj
}

let timer
let pre = 0

/**
 * 延迟执行
 * @param ms
 * @returns {Promise<any>}
 */
export function timeout (ms) {
  return new Promise(resolve => {
    setTimeout(resolve, ms)
  })
}

/**
 * 防抖函数
 * @param {Function} event 执行事件
 * @param {Number} time 延迟时间
 */
 export function debounce(event, time) {
  return (...args) => {
    timer && clearTimeout(timer)
    timer = window.setTimeout(() => {
      event.apply(this, args)
    }, time)
  }
}

/**
 * 节流函数
 * @param {Function} event 执行事件
 * @param {Number} time 延迟时间
 */
export function throttle(event, time) {
  return (...args) => {
    if (Date.now() - pre > time) {
      timer && clearTimeout(timer)
      timer = null
      pre = Date.now()
      event.apply(this, args)
    }
  }
}

/**
 * 选择函数
 * @param {*} list
 * @param {*} key
 * @param {*} value
 * @returns
 */
export function getKeyOfData (list, key, value) {
  let i = -1
  const len = list.length
  let homeItem = {}

  while (++i < len) {
    const item = list[i]

    if (item[key] === value) {
      homeItem = item
      break
    } else if (item.children && item.children.length) {
      const res = getKeyOfData(item.children, key, value)
      if (res[key]) return res
    }
  }

  return homeItem
}
